<?php
use util\Crypt;
use util\CurlUtil;
session_start();

require_once '../bootstrap.php';
require '../util/CurlUtil.php';
require '../util/Crypt.php';
$user_name = trim(isset($_POST['name']) ? $_POST['name'] : '');
$password = trim(isset($_POST['password']) ? $_POST['password'] : '');
$appkey = trim(isset($_POST['appkey']) ? $_POST['appkey'] : '');
$code = trim(isset($_POST['code']) ? $_POST['code'] : '');
$user_cookie = isset($_COOKIE['usinfo']) ? Crypt::decrypt(trim($_COOKIE['usinfo'])) : '';
$ssCode=$_SESSION["ucode"] ;
//echo $user_cookie;
if(!empty($user_cookie)){
	$user_info = json_decode($user_cookie, true);
}
if(!empty($user_info)){
	//有cookie的情况
	$user = $user_info;
	//var_dump($user_info);
}else{
	$data = array(
			'name' => $user_name,
			'password' => $password,
			'appkey' => $appkey,
	);
	if(empty($password)){
		echo json_encode(array('code' => -3, 'message' => 'login fail'));
		exit;
	}
	//var_dump( $_SESSION["ucode"]);
	if($code!=$ssCode )
	{
		echo json_encode(array('code' => -5, 'message' => 'code error'));
		exit;
	}
	//调用oss后台服务验证用户信息
	$response = CurlUtil::curl_post(SERVER_URL . 'login.php', $data);
	if(! empty($response)){
	    $result = json_decode($response, true);
	    if(!empty($result) && $result['code'] == 0){
	    	$user['id'] = $result['user']['id'];
	    	$user['name'] = $result['user']['name'];
	    	setcookie('usinfo', Crypt::encrypt(json_encode($user)),time()+3600);

	    }else{
	    	echo json_encode(array('code' => -1, 'message' => 'login fail'));
	    	exit;
	    }
	}else{
		echo json_encode(array('code' => -1, 'message' => 'login fail'));
		exit;
	}
}

$data = array(
		'user_id' => $user['id'],
		'appkey'=>$appkey
		);

//调用oss后台服务验证用户信息
if(!empty($appkey)){
	$response = CurlUtil::curl_post(SERVER_URL . "skey.php", $data);
	if(!empty($response)){
		$result = json_decode($response, true);
		$result['user'] = $user;
		echo json_encode($result);
	}
}
else{
	echo json_encode(array("code"=>0,"user"=>$user));
}
